package com.leo.platform.authentication.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leo.platform.authentication.client.UserClient;
import com.leo.platform.authentication.common.entity.UserInfo;
import com.leo.platform.authentication.common.utils.JwtUtils;
import com.leo.platform.authentication.properties.JwtProperties;
import com.leo.platform.authentication.service.AuthService;
import com.leo.platform.upms.entity.user.User;

/**
 * @author Administrator
 * @date 2019年7月7日
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties properties;

    /**
     * 用户授权
     * 
     * @param username
     * @param password
     * @return
     */
    public String authentication(String username, String password) {

        try {
            // 1.调用微服务查询用户信息,即尝试查找用户名和匹配的密码
            User user = this.userClient.login(username, password);
            System.out.println(user);
            // 2.查询结果为空，则直接返回null
            if (user == null) {
                return null;
            }
            // 3.查询结果不为空，则生成token
            String token =
                JwtUtils.generateToken(new UserInfo(user.getId(), user.getUsername()), properties.getPrivateKey(),
                    properties.getExpire());
            System.out.println(token);
            return token;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
